
import axios from "axios";
import { ElMessage } from 'element-plus';

const $axios = axios.create({
  baseURL: import.meta.env.VITE_AXIOS_BASEURL,
  timeout: 300000,
});

// 请求拦截
$axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";

$axios.interceptors.request.use((config) => {
  if (config.url !== "/getToken") {
    config.headers.Authorization = localStorage.getItem("token");
    config.headers["access-token"] = localStorage.getItem("token");
  }
  return config;
});

// 响应拦截
$axios.interceptors.response.use(
  (response) => {
    let resData = response.data;
    if(resData.message === 'token失效') {
      ElMessage.warning(resData.message)
      setTimeout(()=> {
        location.href = location.origin
      }, 1000)
    }
    if(resData.status === 403) {
      ElMessage.warning(resData.message)
    }
    return resData
  },
  (error) => {
    console.log(error, 'axios报错');
  }
);

export default $axios;
